<?php
/**
 * TelegramDispatcher.php
 *
 * PHP Version 5.6
 *
 * @category PHP
 * @package  Telegram\Dispatcher
 * @author   ctwj <908504609@qq.com>
 * @license  MIT https://mit-license.org/
 * @link     MIT https://mit-license.org/
 * @date     2018-05-13 22:56:47
 * @modifyby ctwj
 */

namespace Telegram\Dispatcher;

use Telegram\Dispatcher\DispatcherInterface;

/**
 * Wechat Collect
 *
 * @category PHP
 * @package  Telegram\Dispatcher
 * @author   ctwj <908504609@qq.com>
 * @license  MIT https://mit-license.org/
 * @link     MIT https://mit-license.org/
 */
class TelegramDispatcher extends BaseDispatcher implements DispatcherInterface
{

    /**
     * message send to channel, next time can forward to group
     *
     * @var [Telegram\Bot\Objects\Message]
     */
    public $forward = [];

    /**
     * 派发消息
     *
     * @param [array of Telegram\Object\Message] $messages 需要派发的消息列表
     *
     * @return void
     */
    public function dispatch($messages)
    {
        $post_times = 0;
        foreach ($messages as $message) {
            if (isset($this->forward[$message->id])) {
                $this->forward($message->id);
            } else {
                $this->send($message);
            }
        }
    }

    /**
     * 构建发送字符串
     *
     * @param [Telegram\Object\Message] $message 需要派发的消息列表
     *
     * @return array
     */
    public function _buildMessage($message)
    {
        $parse_mode = 'markdown';
        $ext  = $this->destination->extinfo;
        if (isset($ext['parse_mode']) && in_array($ext['parse_mode'], ['markdown', 'html'])) {
            $parse_mode = $ext['parse_mode'];
        }

        $content = '';
        if ($parse_mode == 'markdown') {
            $content = $this->_markdownContent($message);
        }
        if ($parse_mode == 'html') {
            $content = $this->_htmlContent($message);
        }
        
        return [
            'chat_id'       => $this->destination->dest,
            'text'          => $content,
            'parse_mode'    => $parse_mode
        ];
    }

    /**
     * Get markdown format content
     *
     * @param [type] $message message
     *
     * @return string
     */
    private function _markdownContent($message)
    {
        if (!is_null($message->pic) || trim($message->pic) != "") {
            $title = "[$message->title]({$message->pic})" . PHP_EOL;
        } else {
            $title = "**[{$message->title}]($message->message_url)**" . PHP_EOL;
        }
        $auth_category = empty($message->author) ? "" : "#{$message->author}  ";
        $auth_category .= empty($message->auth_category) ? "" : "#{$message->category}";
        $auth_category = empty($message->auth_category) ? "" : PHP_EOL;
        $abstract = $message->abstract . PHP_EOL;

        $link = $message->message_url . PHP_EOL;
        $content = "{$title}{$auth_category}{$abstract}{$link}";
        return $content;
    }

    /**
     * Get html format content
     *
     * @param [type] $message message
     *
     * @return string
     */
    private function _htmlContent($message)
    {
        $title = "<strong>{$message->title}</strong>\r\n";
        $auth_category = "#{$message->author} #{$message->category} \r\n";
        if (trim(str_replace("#", "", $auth_category)) == "") {
            $auth_category = '';
        }
        // $image = "";
        // if (trim($message->pic) == "") {
        //     $image = "![pic]({$message->pic})";
        // }
        $link = "<a href='{$message->message_url}'>$message->message_url</a>\r\n";
        return "{$title}{$auth_category}{$link}";
    }

    /**
     * 发送消息
     *
     * @param [Telegram\Object\Destination] $message 消息
     *
     * @return integer return 1 success, 0 another
     */
    public function send($message)
    {
        getService('logger')->info('SendMessage', ['message_id' => $message->id,'des_id' => $this->destination->id]);
        $mess = $this->_buildMessage($message);
        $result = getService('telegram')->sendMessage($mess);
        if ($this->destination->extinfo == 'channel') {
            $this->forward[$message->id] = $result;
        }
        return 1;
    }

    /**
     * Forward Message
     *
     * @param [integer] $message_id message id
     *
     * @return void
     */
    public function forward($message_id)
    {
        $data = [
            'chat_id'       => $this->destination->dest,
            'from_chat_id'  => $this->forward[$message_id]->getChat()->getId(),
            'message_id'    => $this->forward[$message_id]->getMessageId()
        ];
        getService('logger')->info('ForwardMessage', $data);
        $result = getService('telegram')->forwardMessage($data);
        return 1;
    }
}
